#!/usr/bin/env python3
"""
游戏颜色触发演示脚本
展示如何使用主要颜色检测进行游戏自动化
"""

import time
import pyautogui
from utils.dominant_color_detector import DominantColorDetector

class GameColorTrigger:
    """游戏颜色触发器演示类"""

    def __init__(self):
        self.detector = DominantColorDetector(
            region_size=200,      # 检测区域大小
            k_clusters=3,         # K-Means聚类数量
            cache_duration=0.02   # 20ms缓存，更快响应
        )
        self.running = False
        self.trigger_count = 0

    def setup_target_color(self):
        """设置目标颜色"""
        print("🎯 设置目标颜色")
        print("请将目标颜色移动到屏幕中心，然后按回车确认...")
        input("按回车继续...")

        # 获取当前屏幕中心的主要颜色作为目标
        dominant_color, confidence, detection_info = self.detector.get_dominant_color_at_center()

        if dominant_color:
            self.target_color = dominant_color
            print(f"✅ 目标颜色已设置: RGB{self.target_color}")
            print(f"   检测置信度: {confidence:.3f}")

            # 显示检测到的所有颜色
            all_colors = detection_info.get('all_colors', [])
            weights = detection_info.get('weights', [])

            print(f"   检测区域中的所有颜色:")
            for i, (color, weight) in enumerate(zip(all_colors, weights)):
                marker = "👑" if i == 0 else "  "
                print(f"   {marker} RGB{color} (占比: {weight:.1%})")

            return True
        else:
            print("❌ 无法检测到颜色，请重试")
            return False

    def start_monitoring(self, tolerance=30, trigger_interval=0.5):
        """开始监控和触发"""
        if not hasattr(self, 'target_color'):
            print("❌ 请先设置目标颜色")
            return

        print(f"\n🚀 开始监控颜色触发")
        print(f"   目标颜色: RGB{self.target_color}")
        print(f"   容差: {tolerance}")
        print(f"   触发间隔: {trigger_interval}s")
        print(f"   按 Ctrl+C 停止监控")

        self.running = True
        self.trigger_count = 0
        last_trigger_time = 0

        try:
            while self.running:
                current_time = time.time()

                # 检查颜色匹配 (禁用缓存以获得实时响应)
                is_match, confidence, detection_info = self.detector.is_color_match_dominant(
                    target_color=self.target_color,
                    tolerance=tolerance
                )

                # 强制清除缓存以确保实时检测
                if current_time - getattr(self, '_last_cache_clear', 0) > 0.5:
                    self.detector.clear_cache()
                    self._last_cache_clear = current_time

                if is_match:
                    # 检查触发间隔
                    if current_time - last_trigger_time >= trigger_interval:
                        self.execute_trigger(detection_info)
                        last_trigger_time = current_time
                        self.trigger_count += 1

                # 显示实时状态
                dominant_color = detection_info.get('dominant_color', (0, 0, 0))
                color_distance = detection_info.get('color_distance', 999)
                status = "🎯 匹配" if is_match else "⏳ 监控"

                print(f"\r{status} | 当前: RGB{dominant_color} | 距离: {color_distance:.1f} | 触发次数: {self.trigger_count}   ",
                      end="", flush=True)

                time.sleep(0.1)  # 10Hz检测频率

        except KeyboardInterrupt:
            print(f"\n\n✅ 监控已停止，总触发次数: {self.trigger_count}")
            self.running = False

    def execute_trigger(self, detection_info):
        """执行触发动作"""
        try:
            # 执行左键点击
            pyautogui.click()

            # 记录触发信息
            dominant_color = detection_info.get('dominant_color', (0, 0, 0))
            confidence = detection_info.get('match_confidence', 0)

            print(f"\n🔥 触发! 检测到: RGB{dominant_color}, 置信度: {confidence:.3f}")

        except Exception as e:
            print(f"\n❌ 触发执行失败: {e}")

def demo_fps_game():
    """FPS游戏演示"""
    print("🎮 FPS游戏颜色触发演示")
    print("=" * 50)
    print("这个演示模拟FPS游戏中的敌人检测和自动射击")
    print("1. 设置敌人的特征颜色（如红色血条、特定装备颜色等）")
    print("2. 程序会监控屏幕中心区域")
    print("3. 检测到目标颜色时自动执行左键点击")

    trigger = GameColorTrigger()

    # 设置目标颜色
    if trigger.setup_target_color():
        print(f"\n⚙️ 配置参数:")

        try:
            tolerance = int(input("请输入颜色容差 (推荐30-50): ") or "40")
            interval = float(input("请输入触发间隔秒数 (推荐0.3-1.0): ") or "0.5")
        except:
            tolerance = 40
            interval = 0.5
            print(f"使用默认参数: 容差={tolerance}, 间隔={interval}s")

        # 开始监控
        trigger.start_monitoring(tolerance=tolerance, trigger_interval=interval)

def demo_moba_game():
    """MOBA游戏演示"""
    print("🎮 MOBA游戏颜色触发演示")
    print("=" * 50)
    print("这个演示模拟MOBA游戏中的技能释放时机检测")
    print("例如：检测敌人血条颜色变化、技能冷却完成等")

    trigger = GameColorTrigger()

    # 使用更小的检测区域，适合UI元素
    trigger.detector = DominantColorDetector(
        region_size=100,      # 较小区域适合UI检测
        k_clusters=2,         # 较少聚类适合简单UI
        cache_duration=0.05   # 更快响应
    )

    if trigger.setup_target_color():
        print(f"\n⚙️ MOBA游戏优化配置:")
        print(f"   检测区域: 100x100 像素 (适合UI元素)")
        print(f"   聚类数量: 2 (适合简单颜色)")
        print(f"   响应速度: 快速模式")

        # 使用更严格的参数
        trigger.start_monitoring(tolerance=25, trigger_interval=0.2)

def demo_custom_game():
    """自定义游戏演示"""
    print("🎮 自定义游戏颜色触发演示")
    print("=" * 50)

    trigger = GameColorTrigger()

    print("请选择检测模式:")
    print("1. 精确模式 (小区域，高精度)")
    print("2. 标准模式 (中等区域，平衡)")
    print("3. 广域模式 (大区域，抗噪声)")

    try:
        mode = input("请选择模式 (1-3): ").strip()
    except:
        mode = "2"

    if mode == "1":
        # 精确模式
        trigger.detector = DominantColorDetector(region_size=80, k_clusters=2, cache_duration=0.05)
        default_tolerance = 20
        default_interval = 0.1
        print("✅ 精确模式: 80x80区域, 2聚类, 快速响应")
    elif mode == "3":
        # 广域模式
        trigger.detector = DominantColorDetector(region_size=300, k_clusters=4, cache_duration=0.2)
        default_tolerance = 50
        default_interval = 0.8
        print("✅ 广域模式: 300x300区域, 4聚类, 抗噪声")
    else:
        # 标准模式
        trigger.detector = DominantColorDetector(region_size=200, k_clusters=3, cache_duration=0.1)
        default_tolerance = 35
        default_interval = 0.5
        print("✅ 标准模式: 200x200区域, 3聚类, 平衡性能")

    if trigger.setup_target_color():
        trigger.start_monitoring(tolerance=default_tolerance, trigger_interval=default_interval)

def main():
    """主函数"""
    print("🚀 游戏颜色触发演示程序")
    print("基于 K-Means 主要颜色检测技术")
    print("=" * 50)

    # 检查依赖
    try:
        import sklearn
        print(f"✅ 环境检查通过")
    except ImportError:
        print("❌ 缺少依赖: pip install scikit-learn")
        return

    print("\n请选择演示模式:")
    print("1. FPS游戏模式 (敌人检测)")
    print("2. MOBA游戏模式 (UI检测)")
    print("3. 自定义模式 (可配置)")
    print("4. 退出")

    try:
        choice = input("\n请选择 (1-4): ").strip()
    except:
        choice = "4"

    if choice == "1":
        demo_fps_game()
    elif choice == "2":
        demo_moba_game()
    elif choice == "3":
        demo_custom_game()
    else:
        print("👋 再见!")

if __name__ == "__main__":
    main()
